package ccgl.com.util;

import java.io.BufferedReader;
import java.lang.reflect.Type;

import javax.servlet.http.HttpServletRequest;

import com.google.gson.Gson;

/**
 * json公用类
 * 
 * @author 申鱼川
 * 
 */
public class JsonHelper {
	/**
	 * 从request中读取字符串对象并且返回对象的json字符串
	 * 
	 * @return 返回json字符串
	 * @throws Exception
	 */
	public static String getJsonStrByRequest(HttpServletRequest request) throws Exception {
		StringBuffer json = new StringBuffer();
		String line = null;
		BufferedReader reader = request.getReader();
		while ((line = reader.readLine()) != null) {
			json.append(line);
		}
		return json.toString();
	}

	/**
	 * 从request流中获取对象（该流中是一个json字符串）(GSON)
	 * 
	 * @param clazz Object.class
	 * @return 返回对象
	 * @throws Exception
	 */
	public static <T> T getObjectByServletRequest(HttpServletRequest request, Type clazz)
			throws Exception {
		String jsonValue = getJsonStrByRequest(request);
		return new Gson().fromJson(jsonValue, clazz);
	}
}

